import { Player } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent, GameState } from "@sapi-game/main";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { isAdmin } from "sapi-pro/scripts/func";
import { ElevatorCatConfig, eleConfigManager } from "../configManager";

export class ElevatorCatConfigSetter extends GameComponent<GameState> {
    override onAttach(): void {
        this.subscribe(
            Game.events.buttonPush,
            (e) => {
                const p = e.source as Player;
                if (!isAdmin(p)) return p.sendMessage("你不是管理员，无权修改配置");
                this.showSettingForm(p);
            },
            {
                loc: [366, -58, 149],
                dimensionId: DimensionIds.Overworld,
                sourceType: EntityTypeIds.Player,
            }
        );
        this.updateFloattext();
    }

    showSettingForm(player: Player) {
        // 从 db 获取配置，如果 undefined 使用默认值
        const config = eleConfigManager.getConfig();

        const form = new ModalFormData()
            .title("电梯猫配置")
            .dropdown("生命条数", ["1", "2", "3", "4", "5"], {
                defaultValueIndex: config.lives > 1 ? config.lives - 1 : 0,
            })
            .textField("游戏时长(单位秒)", "输入时间", { defaultValue: config.time.toString() })
            .textField("指南针冷却(单位秒)", "输入时间", {
                defaultValue: config.locateCooldown.toString(),
            })
            .textField("猫猫指南针冷却(单位秒)", "输入时间", {
                defaultValue: config.locateCooldownCat.toString(),
            })
            .textField("攻击后停顿(单位秒)", "输入时间", {
                defaultValue: config.attackCooldown.toString(),
            })
            .toggle("盗铃模式", { defaultValue: config.bellMode });

        form.show(player).then((res) => {
            const data = res.formValues;
            if (!data) return;

            const [healthIdx, timeStr, compassStr, compassCatStr, attackStr, dlToggle] = data;

            // 安全解析函数
            const parsePositiveInt = (v: unknown, fallback: number) => {
                const n = parseInt(String(v), 10);
                return Number.isFinite(n) && n >= 0 ? n : fallback;
            };
            const defaultConfig = eleConfigManager.getDefaultConfig();
            // 解析并验证数值，如果不合法就使用默认值
            const parsed: ElevatorCatConfig = {
                lives: dlToggle ? 1 : parsePositiveInt(healthIdx, defaultConfig.lives - 1) + 1,
                time: parsePositiveInt(timeStr, defaultConfig.time),
                locateCooldown: parsePositiveInt(compassStr, defaultConfig.locateCooldown),
                locateCooldownCat: parsePositiveInt(compassCatStr, defaultConfig.locateCooldownCat),
                attackCooldown: parsePositiveInt(attackStr, defaultConfig.attackCooldown),
                bellMode: Boolean(dlToggle),
            };

            // 保存到 db
            eleConfigManager.setConfig(parsed);
            //更新悬浮文字
            this.updateFloattext();
            player.sendMessage("§a设置成功");
        });
    }

    updateFloattext() {
        const config = eleConfigManager.getConfig();

        const dim = Dimensions.Overworld;
        const floattext =
            dim.getEntities({
                location: { x: 369.0, y: -58.0, z: 148.5 },
                maxDistance: 3,
                type: "game:floattext",
            })[0] ?? dim.spawnEntity("game:floattext", { x: 369.0, y: -58.0, z: 148.5 });

        floattext.nameTag =
            `§d§l游戏配置\n§r` +
            `§c生命条数: ${config.lives}\n` +
            `§3游戏时间: ${config.time}\n` +
            `§e指南针冷却: ${config.locateCooldown}\n` +
            `§c猫猫指南针冷却: ${config.locateCooldownCat}\n` +
            `§2攻击冷却: ${config.attackCooldown}\n` +
            `§6盗铃: ${config.bellMode ? "是" : "否"}`;
    }
}
